package com.wh1200.mybatis.xmlless.model.component

import com.wh1200.mybatis.xmlless.constant.JOIN
import com.wh1200.mybatis.xmlless.enums.JoinType
import com.wh1200.mybatis.xmlless.model.JoinOnLogicDeleteCondition
import com.wh1200.mybatis.xmlless.model.MethodInfo
import com.wh1200.mybatis.xmlless.model.TableName

/**
 *
 * @author 吴昊
 * @date 2023/12/4 22:43
 * @since v0.0.0
 * @version 1.0
 */
class JoinDeclaration(
    private val type: JoinType,
    val joinTable: TableName,
    val joinCondition: JoinOnConditionDeclaration,
    private val joinSelect: List<JoinDeclaration> = listOf()
) : ISqlPart() {

  var logicDeleteConditionSql: JoinOnLogicDeleteCondition? = null

  override fun toSql(methodInfo: MethodInfo): String {
    return toSql(joinCondition.toSql(methodInfo))
  }

  override fun toSql(): String {
    return toSql(joinCondition.toSql())
  }

  private fun toSql(conditionString: String): String {
    val finalConditionString = if (logicDeleteConditionSql != null) {
      "$conditionString AND ${logicDeleteConditionSql?.toSql()}"
    } else {
      conditionString
    }
    val sql = JOIN.format(
        type.name,
        joinTable.toSql(),
        finalConditionString
    ).trim()
    if (joinSelect.isEmpty()) {
      return sql.trim()
    }
    return (sql + "\n" + joinSelect.joinToString("\n") { it.toSql() }).trim()
  }

}
